package com.xunshangwang.pinhaohuo.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.xunshangwang.pinhaohuo.R;
import com.xunshangwang.pinhaohuo.adapters.GoodsAdapter;
import com.xunshangwang.pinhaohuo.decorations.GoodsItemDecoration;
import com.xunshangwang.pinhaohuo.entity.Goods;
import com.xunshangwang.pinhaohuo.entity.Shop;
import com.xunshangwang.pinhaohuo.entity.ShopDetail;
import com.xunshangwang.pinhaohuo.http.HttpTool;
import com.xunshangwang.pinhaohuo.http.JsonHttpHandler;
import com.xunshangwang.pinhaohuo.transformation.RoundedTransformation;
import com.xunshangwang.pinhaohuo.widgets.LMSizeRecyclerView;
import com.xunshangwang.pinhaohuo.widgets.RefreshLayout;

import org.json.JSONObject;

import java.util.List;
import java.util.Queue;

import cz.msebera.android.httpclient.Header;
import tool.library.ToastTool;
import tool.library.adapter.BaseRecyclerAdapter;
import tool.library.widget.LoadRecyclerView;

/**
 * Created by xzp on 16/1/26.
 */
public class ShopDetailActivity extends BaseActivity implements BaseRecyclerAdapter.OnItemClickListener,SwipeRefreshLayout.OnRefreshListener,
        LoadRecyclerView.OnLoadListener,View.OnClickListener{
    private RefreshLayout mRefresh;
    private LMSizeRecyclerView mRecycler;
    private ImageView mShopImage;
    private Button mCollectBtn;
    private TextView mShopNameText,mSellCountText;
    private DetailAdapter mAdapter;
    private ShopDetail mShopDetail;
    private String mShopId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_detail);
        mShopId=getIntent().getStringExtra("id");
        mRecycler= (LMSizeRecyclerView) this.findViewById(R.id.shop_goods_list);
        mRecycler.addItemDecoration(new GoodsItemDecoration(this){
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position=parent.getChildAdapterPosition(view);
                if(position!=0 && position!=parent.getAdapter().getItemCount()-1)
                    super.getItemOffsets(outRect, view, parent, state);
            }
        });
        mRecycler.setLayoutManager(new LinearLayoutManager(this));
        mRecycler.setOnLoadListener(this);
        mRefresh= (RefreshLayout) this.findViewById(R.id.refresh_layout);
        mRefresh.setOnRefreshListener(this);
        mAdapter=new DetailAdapter(this);
        mAdapter.setOnItemClickListener(this);
        mRecycler.setAdapter(mAdapter);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefresh.setRefreshing(true);
                onRefresh();
            }
        }, 150);
    }

    @Override
    public void onItemClick(BaseRecyclerAdapter adapter, View item, int position) {
        position=position-1;
//        Intent intent=new Intent(this,GoodsDetailActivity.class);
//        intent.putExtra("id", mAdapter.getList().get(position).getGoods_id());
//        startActivity(intent);
        Intent intent=new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("pin://www.xunshangwang.com/goods/detail?id=" + mAdapter.getList().get(position).getGoods_id()));
        startActivity(intent);
    }

    @Override
    public void onLoad(LoadRecyclerView recyclerView) {
        requestLoad();
    }

    @Override
    public void onRefresh() {
        requestDetail();
    }

    @Override
    public void onClick(View v) {
        requestCollect();
    }
    private void requestCollect(){
        if(mShopDetail==null || mShopDetail.getShop_info()==null)
            return;
        if(!getMainApplication().isLogin()) {
            ToastTool.showToast("请登录后再收藏");
            return;
        }
        StringBuilder builder=new StringBuilder("?g=Api&m=Favorites&a=toggleFavorites");
        builder.append("&fav_type=0");
        builder.append("&fav_id="+mShopId);
        builder.append("&token="+getMainApplication().getToken());
        HttpTool.get(this, builder.toString(), new JsonHttpHandler<String>() {
            @Override
            public void onStart() {
                super.onStart();
                mCollectBtn.setEnabled(false);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mCollectBtn.setEnabled(true);
            }

            @Override
            public String parseData(JSONObject object) throws Throwable {
                return object.getString("is_favorites");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, String response) {
                updateCollectState(TextUtils.equals("1",response));
                mShopDetail.getShop_info().setIs_favorites(response);
            }
        });
    }
    private void requestDetail(){
        StringBuilder builder=new StringBuilder("?g=Api&m=Shop&a=goods");
        builder.append("&shop_id="+mShopId);
        builder.append("&offset=0");
        builder.append("&size="+LMSizeRecyclerView.SIZE);
        if(getMainApplication().isLogin())
            builder.append("&token="+getMainApplication().getToken());
        HttpTool.get(this, builder.toString(), new JsonHttpHandler<ShopDetail>() {

            @Override
            public void onFinish() {
                super.onFinish();
                mRefresh.setRefreshing(false);
            }

            @Override
            public ShopDetail parseData(JSONObject object) throws Throwable {
                return JSON.parseObject(object.toString(),ShopDetail.class);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, ShopDetail response) {
                if(response!=null){
                    mShopDetail=response;
                    Shop shop=mShopDetail.getShop_info();
                    if(shop!=null) {
                        mShopNameText.setText(shop.getShop_name());
                        mSellCountText.setText("销量:  "+shop.getSell_count());
                        Glide.with(ShopDetailActivity.this).load(shop.getShop_face()).centerCrop()
                                .transform(new RoundedTransformation(ShopDetailActivity.this,R.dimen.shop_face_rounded_size))
                                .into(mShopImage);
                        updateCollectState(TextUtils.equals(shop.getIs_favorites(),"1"));
                    }
                    mAdapter.setList(mShopDetail.getGoods());
                    mRecycler.loadFinish(mShopDetail.getGoods());
                }
            }
        });
    }
    private void requestLoad(){
        StringBuilder builder=new StringBuilder("?g=Api&m=Shop&a=goods");
        builder.append("&shop_id="+mShopId);
        builder.append("&offset="+mAdapter.getListSize());
        builder.append("&size="+LMSizeRecyclerView.SIZE);
        if(getMainApplication().isLogin())
            builder.append("&token="+getMainApplication().getToken());
        HttpTool.get(this, builder.toString(), new JsonHttpHandler<List<Goods>>() {
            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, List<Goods> errorResponse) {
                super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
                mRecycler.loadFinish();
            }

            @Override
            public List<Goods> parseData(JSONObject object) throws Throwable {
                return JSON.parseArray(object.getString("goods"),Goods.class);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Goods> response) {
                mAdapter.addAll(response);
                mRecycler.loadFinish(response);
            }
        });
    }
    private void updateCollectState(boolean isCollect){
        if(isCollect){
            mCollectBtn.setBackgroundResource(R.drawable.shop_collect_bg);
            mCollectBtn.setTextColor(ContextCompat.getColor(this, R.color.gray));
            mCollectBtn.setText("取消收藏");
        }else {
            mCollectBtn.setBackgroundResource(R.drawable.shop_not_collect_bg);
            mCollectBtn.setTextColor(ContextCompat.getColor(this, R.color.red));
            mCollectBtn.setText("收藏店铺");
        }
    }
    private class DetailAdapter extends GoodsAdapter{
        private ShopHolder mShopHolder;
        public DetailAdapter(Context context) {
            super(context);
            View view=getLayoutInflater().inflate(R.layout.shop_item,mRecycler,false);
            mShopHolder=new ShopHolder(view);
        }

        @Override
        public int getItemCount() {
            return super.getItemCount()+1;
        }

        @Override
        public int getViewType(int position) {
            if(position==0)
                return 0;
            else
                return 1;
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            if(viewType==0)
                return mShopHolder;
            else
                return super.onCreateHolder(parent,viewType);
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder holder, int position) {
            if(getViewType(position)==0) {
                return;
            }
            else {
                position=position-1;
                super.onBindHolder(holder, position);
            }

        }
        private class ShopHolder extends RecyclerView.ViewHolder{

            public ShopHolder(View itemView) {
                super(itemView);
                mShopImage = (ImageView) itemView.findViewById(R.id.shop_image);
                mCollectBtn = (Button) itemView.findViewById(R.id.shop_collect_btn);
                mCollectBtn.setOnClickListener(ShopDetailActivity.this);
                mShopNameText = (TextView) itemView.findViewById(R.id.shop_name_text);
                mSellCountText = (TextView) itemView.findViewById(R.id.shop_sell_count_text);
            }
        }
    }
}
